﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;

namespace LightSO.Library.Common
{
    /// <summary>
    /// 转换为Excel文件字节流
    /// </summary>
    public class FileHelper
    {
        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="content"></param>
        /// <param name="filename"></param>
        /// <param name="mediaType"></param>
        /// <returns></returns>
        public static HttpResponseMessage Download(HttpRequestMessage httpRequestMessage, byte[] content, string filename, string mediaType)
        {
            var response = httpRequestMessage.CreateResponse(HttpStatusCode.OK);
            response.Content = new ByteArrayContent(content);
            response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = filename;

            response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(mediaType);

            return response;
        }

        /// <summary>
        /// 转换为Excel字节流
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="defaultSheetName"></param>
        /// <returns></returns>
        public byte[] ToExcel<T>(List<T> list, string defaultSheetName = null)
        {
            HSSFWorkbook workbook = new HSSFWorkbook();

            ICellStyle styleCell = workbook.CreateCellStyle(); // 获取单元格 并设置样式

            styleCell.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; //居中

            styleCell.VerticalAlignment = VerticalAlignment.Top; //垂直居中

            if (string.IsNullOrWhiteSpace(defaultSheetName))
                defaultSheetName = "table";

            if (list != null && list.Count > 0)
            {
                var columns = GetColumns(list[0].GetType());
                int rowNum = 1, sheetNum = 1;
                ISheet currentSheet = null;
                foreach (var item in list)
                {
                    var sheetName = defaultSheetName.Replace("/", "").Replace("-", "");
                    if (currentSheet == null || currentSheet.SheetName.IndexOf(sheetName) != 0)
                    {
                        currentSheet = CreateSheet(workbook, sheetName, columns);
                        rowNum = 1;
                    }
                    else if (rowNum > 65534)
                    {
                        currentSheet = CreateSheet(workbook, string.Format("{0}({1})", sheetName, sheetNum), columns);
                        rowNum = 1;
                        sheetNum++;
                    }

                    IRow row = currentSheet.CreateRow(rowNum);
                    
                    for (int i = 0; i < columns.Count; i++)
                    {
                        ICell cell = row.CreateCell(i);

                        var value = GetValue<T>(columns, item, i);

                        var currentWidth = currentSheet.GetColumnWidth(i);
                        if (value.Length * 258 > currentWidth)
                            currentWidth = value.Length * 258;

                        currentSheet.SetColumnWidth(i, currentWidth);

                        cell.SetCellValue(value);

                        cell.CellStyle = styleCell;
                    }

                    rowNum++;
                }
            }

            MemoryStream file = new MemoryStream();

            workbook.Write(file);

            return file.GetBuffer();
        }


        /// <summary>
        /// 转换为Html
        /// </summary>
        public string ToHtml<T>(T entity, string defaultSheetName = null) where T:class, new()
        {
            var list = new List<T>();
            list.Add(entity);
            return ToHtml(list, defaultSheetName);
        }

        /// <summary>
        /// 转换为Html
        /// </summary>
        public string ToHtml<T>(List<T> list, string defaultSheetName = null) where T : class, new()
        {
            StringBuilder html = new StringBuilder();

            html.AppendFormat("<H2>{0}</H2>\r\n", defaultSheetName);
            html.AppendLine("<TABLE border='1'  cellspacing='0' cellpadding='5' bordercolor='#000000' style='BORDER-COLLAPSE: collapse'>");
            if (list != null && list.Count > 0)
            {
                var columns = GetColumns(list[0].GetType());
                html.AppendLine("   <TR>");
                foreach (var item in columns)
                {
                    html.Append("       <TD>");
                    html.Append(item.Attribute.Name);
                    html.AppendLine("</TD>");
                }
                html.AppendLine("   </TR>");
                foreach (var item in list)
                {
                    html.AppendLine("   <TR>");
                    for (int i = 0; i < columns.Count; i++)
                    {
                        html.Append("       <TD>");
                        html.Append(GetValue<T>(columns, item, i));
                        html.AppendLine("</TD>");
                    }
                    html.AppendLine("   </TR>");
                }
            }

            html.AppendLine("</TABLE>");

            return html.ToString();
        }

        private string GetValue<T>(List<CellInfo> columns, T item, int i)
        {
            var value = columns[i].Property.GetValue(item);

            if (value.GetType().BaseType != null && value.GetType().BaseType.Equals(typeof(Enum)))
            {
                var helper = new EnumHelper();
                value = helper.Text((Enum)value);
            }

            if (!string.IsNullOrWhiteSpace(columns[i].Attribute.Func))
            {
                var method = item.GetType().GetMethod(columns[i].Attribute.Func);
                if (method != null)
                {
                    value = method.Invoke(item, new object[] { value });
                }
            }

            if (!string.IsNullOrWhiteSpace(columns[i].Attribute.Format))
            {
                if (value.GetType().Equals(typeof(DateTime)))
                    value = ((DateTime)value).ToString(columns[i].Attribute.Format);
                else if (value.GetType().Equals(typeof(float)))
                    value = ((float)value).ToString(columns[i].Attribute.Format);
                else if (value.GetType().Equals(typeof(double)))
                    value = ((double)value).ToString(columns[i].Attribute.Format);
                else
                    value = string.Format(columns[i].Attribute.Format, value);
            }

            return value.ToString();
        }

        private List<CellInfo> GetColumns(Type type)
        {
            var result = new List<CellInfo>();

            var properties = type.GetProperties();
            if (properties == null)
                return result;

            foreach (var item in properties)
            {
                var attr = Attribute.GetCustomAttribute(item, typeof(TextAttribute), true) as TextAttribute;
                if (attr == null)
                    continue;

                var info = new CellInfo
                {
                    Attribute = attr,
                    Property = item,
                };
                result.Add(info);
            }

            return result;
        }

        private ISheet CreateSheet(HSSFWorkbook workbook, string sheetName, List<CellInfo> columns)
        {
            var currentSheet = workbook.CreateSheet(sheetName);
            IRow rowHead = currentSheet.CreateRow(0);

            //初始化列
            for (int i = 0; i < columns.Count; i++ )
            {
                var item = columns[i];
                var cell = rowHead.CreateCell(i);

                if (!string.IsNullOrWhiteSpace(item.Attribute.Name))
                {
                    cell.SetCellValue(item.Attribute.Name);
                    if (item.Attribute.Name.Length * 258 > currentSheet.GetColumnWidth(i))
                    {
                        currentSheet.SetColumnWidth(i, item.Attribute.Name.Length * 258 + 20);
                    }
                    continue;
                }

                cell.SetCellValue(item.Property.Name);
                if (item.Property.Name.Length * 258 > currentSheet.GetColumnWidth(i))
                {
                    currentSheet.SetColumnWidth(i, item.Property.Name.Length * 258 + 20);
                }
            }

            return currentSheet;
        }

        private class CellInfo
        {
            public TextAttribute Attribute { get; set; }

            public PropertyInfo Property { get; set; }
        }
    }
}
